//
//  PhotoViewController.m
//  一键车讯
//
//  Created by 江玉元 on 14/11/4.
//  Copyright (c) 2014年 lanou.3g.com. All rights reserved.
//

#import "PhotoViewController.h"
#import "PhotoDetailViewController.h"
#import "GallerySliderCell.h"
#import "GallerySliderLayout.h"
#import "macro.h"
#import "NetHandler.h"
#import "MJRefresh.h"
#import "Photo.h"
#import "UIImageView+WebCache.h"
@interface PhotoViewController ()<GallerySliderCellDelegate, GallerySliderLayoutDelegate, UICollectionViewDataSource, UICollectionViewDelegate>


@property (nonatomic, retain)UICollectionView *galleryCollectionView;
@property (nonatomic, retain)NSMutableArray *dataArray;
@property (nonatomic, retain)GallerySliderLayout *layout;
@end

@implementation PhotoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.dataArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"图赏";
    [self startConnection];
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(barLeftButtonItemAction:)] autorelease];
    
}

- (void)startConnection
{   // 接口解析
    NSString *str = @"http://agent1.pconline.com.cn:8941/pcautophoto/iphone_cate_json.jsp?id=89";
    [NetHandler networkWithURL:str completion:^(id result) {
        NSMutableArray *dicArr = [result objectForKey:@"groups"];
        for (NSDictionary *dic in dicArr) {
            Photo *photo = [[Photo alloc] initWithDictionary:dic];
            [self.dataArray addObject:photo];
        }
        // 刷新数据
        [self initCollectionView];
        [self.galleryCollectionView reloadData];
        [self setupRefresh];
        [self.layout setContentSize:self.dataArray.count];
       // NSLog(@"*** %@", self.dataArray);
    }];
}

- (void)initCollectionView
{
     self.layout = [[GallerySliderLayout alloc] init];
    [_layout setContentSize:20];
    self.galleryCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, CELL_WIDTH, CGRectGetHeight([UIScreen mainScreen].bounds)) collectionViewLayout:_layout];
    self.galleryCollectionView.backgroundColor = [UIColor whiteColor];
    [self.galleryCollectionView registerClass:[GallerySliderCell class] forCellWithReuseIdentifier:@"CELL"];
    self.galleryCollectionView.delegate = self;
    self.galleryCollectionView.dataSource = self;
    [self.view addSubview:self.galleryCollectionView];
    [self.layout release];
    [self.galleryCollectionView release];
}

//UINavigationItem方法
- (void)barLeftButtonItemAction:(UIBarButtonItem *)barButton
{
    // 返回首页
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.galleryCollectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.galleryCollectionView headerBeginRefreshing];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.galleryCollectionView.headerPullToRefreshText = @"下拉以刷新...";
    self.galleryCollectionView.headerReleaseToRefreshText = @"松开即可刷新...";
    self.galleryCollectionView.headerRefreshingText = @"刷新中...";
    
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.galleryCollectionView reloadData];
        
        [_galleryCollectionView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.galleryCollectionView headerEndRefreshing];
    });
}


#pragma -mark UICollectionView 代理方法



- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count + 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return CGSizeMake(CELL_WIDTH, HEADER_HEIGHT);
    }else if (indexPath.row == 1){
        return CGSizeMake(CELL_WIDTH, CELL_CURRHEIGHT);
    } else{
        return CGSizeMake(CELL_WIDTH, CELL_HEIGHT);
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GallerySliderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    cell.delegate = self;
    cell.tag = indexPath.row;
    [cell setIndex:indexPath.row];
    [cell reset];
    if (indexPath.row == 0) {
        [cell revisePositionAtFirstCell];
    } else{
        Photo *photo = self.dataArray[indexPath.row - 1];
        NSString *str = photo.image;
        NSString *name = photo.name;
        NSString *count = photo.count;
        [cell.myImageView setImageWithURL:[NSURL URLWithString:str]];
        [cell setNameLabel:name];
        [cell setDescLabel:count];
        
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoDetailViewController *photoVC = [[PhotoDetailViewController alloc] init];
    photoVC.photo = [self.dataArray objectAtIndex:indexPath.row - 1];
    [self.navigationController pushViewController:photoVC animated:YES];
    [photoVC release];
}

- (void)dealloc
{
    [_galleryCollectionView release];
    [_dataArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
